//package com.yupi.qingApiGateway;
//
//
//import com.qing.qingapiclientsdk.utils.SignUtils;
//import com.qing.qingapicommon.model.entity.InterfaceInfo;
//import com.qing.qingapicommon.model.entity.User;
//import com.qing.qingapicommon.service.InnerInterfaceInfoService;
//import com.qing.qingapicommon.service.InnerUserInterfaceInfoService;
//import com.qing.qingapicommon.service.InnerUserService;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.dubbo.config.annotation.DubboReference;
//import org.reactivestreams.Publisher;
//import org.springframework.cloud.gateway.filter.GatewayFilterChain;
//import org.springframework.cloud.gateway.filter.GlobalFilter;
//import org.springframework.core.Ordered;
//import org.springframework.core.io.buffer.DataBuffer;
//import org.springframework.core.io.buffer.DataBufferFactory;
//import org.springframework.core.io.buffer.DataBufferUtils;
//import org.springframework.http.HttpHeaders;
//import org.springframework.http.HttpStatus;
//import org.springframework.http.server.reactive.ServerHttpRequest;
//import org.springframework.http.server.reactive.ServerHttpResponse;
//import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
//import org.springframework.stereotype.Component;
//import org.springframework.web.server.ServerWebExchange;
//import reactor.core.publisher.Flux;
//import reactor.core.publisher.Mono;
//
//import java.nio.charset.StandardCharsets;
//import java.util.ArrayList;
//import java.util.Arrays;
//import java.util.List;
//
//@Slf4j
//@Component
//public class CustomGlobalFilter implements GlobalFilter, Ordered {
//
//    @DubboReference
//    private InnerUserService innerUserService;
//    @DubboReference
//    private InnerInterfaceInfoService interfaceInfoService;
//    @DubboReference
//    private InnerUserInterfaceInfoService innerUserInterfaceInfoService;
//    private static final List<String> IP_WHILE_LIST = Arrays.asList("127.0.0.1");
//
//    private static final String INTERFACE_HOST = "http://localhost:8123";
//
//    @Override
//    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        log.info("GlobalFilter is running");
////       1请求日志
//        ServerHttpRequest request = exchange.getRequest();
//        String path = INTERFACE_HOST + request.getPath().value();
//        String method = request.getMethod().toString();
//        //        所有的请求头信息都会在exchange里面
//        log.info("请求唯一标识"+request.getId());
//        log.info("请求路径"+request.getPath().value());
//        log.info("请求方法"+request.getMethod());
//        log.info("请求参数"+request.getQueryParams());
//        log.info("请求来源地址"+request.getLocalAddress().getHostString());
//        log.info("请求来源地址"+request.getRemoteAddress().getHostString());
//        String address =request.getLocalAddress().getHostString();
//        ServerHttpResponse response = exchange.getResponse();
////        log.info("请求路径"+request.getPath().value());
////        2(黑白名单)
//        if(!IP_WHILE_LIST.contains(address)){
//            response.setStatusCode(HttpStatus.FORBIDDEN);
////            这个错误是403
//            return response.setComplete();
//        }
////        这里最好用白名单限制，就是只给允许的用户通过
////        3用户鉴权（判断 ak sk 是否合法
////        把模拟接口的逻辑搬过来
////        HttpHeaders headers =request.getHeaders();
//////        因为header是键值对 所以那第一个
////        String accessKey = headers.getFirst("accessKey");
//////        String secretkey = request.getHeader("secretKey");
////        String nonce = headers.getFirst("nonce");
////        String timeStamp = headers.getFirst("timeStamp");
////        String sign = headers.getFirst("sign");
////        String body =headers.getFirst("body");
//        HttpHeaders headers = request.getHeaders();
//        String accessKey = headers.getFirst("accessKey");
//        String nonce = headers.getFirst("nonce");
//        String timestamp = headers.getFirst("timestamp");
//        String sign = headers.getFirst("sign");
//        String body = headers.getFirst("body");
////        String path = headers.getFirst("url");
////        String method = headers.getFirst("method");
////        TODO 根据实际情况王数据库中差是否已分配给用户
//        User invokeUser = null;
//        try {
//            invokeUser = innerUserService.getInvokeUser(accessKey);
//        }catch (Exception e){
//            log.error("获取用户失败",e);
//        }
////        if(!accessKey.equals("qing") ){
////            return handleNoAuth(response);
////        } 这里是固定测试的而已，我们实际从数据库那，现在就不用了
//        if(Long.parseLong(nonce) > 10000L){
//            return handleNoAuth(response);
//        }
//        Long FIVE_MINUTES= 60*5L;
////        TODO 时间和当前时间不能超过5分钟 打勾
//        Long currentTime = System.currentTimeMillis()/1000;
//        if(currentTime - Long.parseLong(timestamp) > FIVE_MINUTES){
//            return handleNoAuth(response);
//        }
////        TODO 实际情况中是否从数据库中查出secretKey（根据ak来查）
//        String secretKey = invokeUser.getSecretKey();
//        String seversign = SignUtils.getSign(body,secretKey);
////        用实际的了，不用abcdefgh这样固定的
//        if(!sign.equals(seversign)){
//            return handleNoAuth(response);
//        }
//        //        4.请求的模拟接口是否存在
////        TODO 从数据库中查询模拟接口是否存在。以及请求方法是否匹配（还可以校验请求参数）
////       用一个try catch来判断
//        InterfaceInfo interfaceInfo =null;
//        try {
//             interfaceInfo = interfaceInfoService.getInterfaceInfo(path,method);
//
//        }catch (Exception e){
//            log.error("获取接口信息失败");
//        }
//        if(interfaceInfo==null){
//            return handleNoAuth(response);
//        }
//        //        5.请求转发，调用模拟接口
////        Mono<Void> filter = chain.filter(exchange);
//        log.info("响应"+ response.getStatusCode());
//
//        //        6.相应日志
//        return handleResponse(exchange,chain,interfaceInfo.getId(),invokeUser.getId());
//        //        7调用成功 接口调用次数+1
////        TODO 调用成功，接口调用次数+1 invokeCount
//
//        //        9调用失败，返回一个规范的错误码
////        if(response.getStatusCode()==HttpStatus.OK){
////
////        }else {
////            return handleInvokeError(response);
////        }
////        return filter;
//
//    }
//
//    /**
//     * 处理响应
//     *
//     * @param exchange
//     * @param chain
//     * @return
//     */
//    public Mono<Void> handleResponse(ServerWebExchange exchange, GatewayFilterChain chain,long userId,long interfaceId) {
//        try {
//            ServerHttpResponse originalResponse = exchange.getResponse();
//            // 缓存数据的工厂
//            DataBufferFactory bufferFactory = originalResponse.bufferFactory();
//            // 拿到响应码
//            HttpStatus statusCode = originalResponse.getStatusCode();
//            if (statusCode == HttpStatus.OK) {
//                // 装饰，增强能力
//                ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
//                    // 等调用完转发的接口后才会执行,所以是不会先进入这个方法的而是进入下面的那个方法
//
//                    @Override
//                    public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
//                        log.info("body instanceof Flux: {}", (body instanceof Flux));
//                        if (body instanceof Flux) {
//                            Flux<? extends DataBuffer> fluxBody = Flux.from(body);
//                            // 往返回值里写数据
//                            // 拼接字符串
//                            return super.writeWith(
//                                    fluxBody.map(dataBuffer -> {
//                                        // 7. 调用成功，接口调用次数 + 1 invokeCount
//                                        try {
//                                            innerUserInterfaceInfoService.invokeCount(interfaceId,userId);
//                                        } catch (Exception e) {
//                                            log.error("invokeCount error", e);
//                                        }
//                                        byte[] content = new byte[dataBuffer.readableByteCount()];
//                                        dataBuffer.read(content);
//                                        DataBufferUtils.release(dataBuffer);//释放掉内存
//                                        // 构建日志
//                                        StringBuilder sb2 = new StringBuilder(200);
//                                        sb2.append("<--- {} {} \n");
//                                        List<Object> rspArgs = new ArrayList<>();
//                                        rspArgs.add(originalResponse.getStatusCode());
//                                        String data = new String(content, StandardCharsets.UTF_8); //data
//                                        sb2.append(data);
//                                        log.info(sb2.toString(),rspArgs.toArray());
//                                        // 打印日志
//                                        log.info("响应结果：" + data);
//                                        return bufferFactory.wrap(content);
//                                    }));
//                        } else {
//                            // 8. 调用失败，返回一个规范的错误码
//                            log.error("<--- {} 响应code异常", getStatusCode());
//                        }
//                        return super.writeWith(body);
//                    }
//                };
//                // 设置 response 对象为装饰过的
//                log.info("进入 handleResponse 方法");
//                return chain.filter(exchange.mutate().response(decoratedResponse).build());
//            }
//            return chain.filter(exchange); // 降级处理返回数据
//        } catch (Exception e) {
//            log.error("网关处理响应异常" + e);
//            return chain.filter(exchange);
//        }
//    }
//
//        public Mono<Void> handleNoAuth(ServerHttpResponse response) {
//            response.setStatusCode(HttpStatus.FORBIDDEN);
//            return response.setComplete();
//        }
//        public Mono<Void> handleInvokeError(ServerHttpResponse response) {
//            response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
//            return response.setComplete();
//        }
//        @Override
//        public int getOrder() {
//            return 0;
//        }
//}
//
//
//
//
//
package com.qing.springbootinit.qingApiGateway;


import com.qing.qingapiclientsdk.utils.SignUtils;
import com.qing.qingapicommon.model.entity.InterfaceInfo;
import com.qing.qingapicommon.model.entity.User;
import com.qing.qingapicommon.service.InnerInterfaceInfoService;
import com.qing.qingapicommon.service.InnerUserInterfaceInfoService;
import com.qing.qingapicommon.service.InnerUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 全局过滤
 * @author qingfengzy
 */
@Slf4j
@Component
public class CustomGlobalFilter implements GlobalFilter, Ordered {

    @DubboReference
    private InnerUserService innerUserService;

    @DubboReference
    private InnerInterfaceInfoService innerInterfaceInfoService;

    @DubboReference
    private InnerUserInterfaceInfoService innerUserInterfaceInfoService;

    private static final List<String> IP_WHITE_LIST = Arrays.asList("127.0.0.1");

    private static final String INTERFACE_HOST = "http://localhost:8123";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1. 请求日志
        ServerHttpRequest request = exchange.getRequest();
        String path = INTERFACE_HOST + request.getPath().value();
        String method = request.getMethod().toString();
        log.info("请求唯一标识：" + request.getId());
        log.info("请求路径：" + path);
        log.info("请求方法：" + method);
        log.info("请求参数：" + request.getQueryParams());
        String sourceAddress = request.getLocalAddress().getHostString();
        log.info("请求来源地址：" + sourceAddress);
        log.info("请求来源地址：" + request.getRemoteAddress());
//        log.info("请求来源地址：" + request.getHeaders().get);
        ServerHttpResponse response = exchange.getResponse();
        // 2. 访问控制 - 黑白名单
        if (!IP_WHITE_LIST.contains(sourceAddress)) {
            response.setStatusCode(HttpStatus.FORBIDDEN);
            return response.setComplete();
        }
        // 3. 用户鉴权（判断 ak、sk 是否合法）
        HttpHeaders headers = request.getHeaders();
        String accessKey = headers.getFirst("accessKey");
        String nonce = headers.getFirst("nonce");
        String timestamp = headers.getFirst("timestamp");
        String sign = headers.getFirst("sign");
        String body = headers.getFirst("body");
        // todo 实际情况应该是去数据库中查是否已分配给用户
        User invokeUser = null;
        try {
            invokeUser = innerUserService.getInvokeUser(accessKey);
        } catch (Exception e) {
            log.error("getInvokeUser error", e);
        }
        if (invokeUser == null) {
            return handleNoAuth(response);
        }
//        if (!"qing".equals(accessKey)) {
//            return handleNoAuth(response);
//        }
        if (Long.parseLong(nonce) > 10000L) {
            return handleNoAuth(response);
        }
        // 时间和当前时间不能超过 5 分钟
        Long currentTime = System.currentTimeMillis() / 1000;
        final Long FIVE_MINUTES = 60 * 5L;
        if ((currentTime - Long.parseLong(timestamp)) >= FIVE_MINUTES) {
            return handleNoAuth(response);
        }
        // 实际情况中是从数据库中查出 secretKey
        String secretKey = invokeUser.getSecretKey();
        String serverSign = SignUtils.getSign(body, secretKey);
        if (sign == null || !sign.equals(serverSign)) {
            return handleNoAuth(response);
        }
        // 4. 请求的模拟接口是否存在，以及请求方法是否匹配
        InterfaceInfo interfaceInfo = null;
        try {
            interfaceInfo = innerInterfaceInfoService.getInterfaceInfo(path, method);
        } catch (Exception e) {
            log.error("getInterfaceInfo error", e);
        }
        if (interfaceInfo == null) {
            return handleNoAuth(response);
        }
        // todo 是否还有调用次数
        // 5. 请求转发，调用模拟接口 + 响应日志
        //        Mono<Void> filter = chain.filter(exchange);
        //        return filter;
        return handleResponse(exchange, chain, interfaceInfo.getId(), invokeUser.getId());

    }

    /**
     * 处理响应
     *
     * @param exchange
     * @param chain
     * @return
     */
    public Mono<Void> handleResponse(ServerWebExchange exchange, GatewayFilterChain chain, long interfaceInfoId, long userId) {
        try {
            ServerHttpResponse originalResponse = exchange.getResponse();
            // 缓存数据的工厂
            DataBufferFactory bufferFactory = originalResponse.bufferFactory();
            // 拿到响应码
            HttpStatus statusCode = originalResponse.getStatusCode();
            if (statusCode == HttpStatus.OK) {
                // 装饰，增强能力
                ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
                    // 等调用完转发的接口后才会执行
                    @Override
                    public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                        log.info("body instanceof Flux: {}", (body instanceof Flux));
                        if (body instanceof Flux) {
                            Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                            // 往返回值里写数据
                            // 拼接字符串
                            return super.writeWith(
                                    fluxBody.map(dataBuffer -> {
                                        // 7. 调用成功，接口调用次数 + 1 invokeCount
                                        try {
                                            innerUserInterfaceInfoService.invokeCount(interfaceInfoId, userId);
                                        } catch (Exception e) {
                                            log.error("invokeCount error", e);
                                        }
                                        byte[] content = new byte[dataBuffer.readableByteCount()];
                                        dataBuffer.read(content);
                                        DataBufferUtils.release(dataBuffer);//释放掉内存
                                        // 构建日志
                                        StringBuilder sb2 = new StringBuilder(200);
                                        List<Object> rspArgs = new ArrayList<>();
                                        rspArgs.add(originalResponse.getStatusCode());
                                        String data = new String(content, StandardCharsets.UTF_8); //data
                                        sb2.append(data);
                                        // 打印日志
                                        log.info("响应结果：" + data);
                                        return bufferFactory.wrap(content);
                                    }));
                        } else {
                            // 8. 调用失败，返回一个规范的错误码
                            log.error("<--- {} 响应code异常", getStatusCode());
                        }
                        return super.writeWith(body);
                    }
                };
                // 设置 response 对象为装饰过的
                return chain.filter(exchange.mutate().response(decoratedResponse).build());
            }
            return chain.filter(exchange); // 降级处理返回数据
        } catch (Exception e) {
            log.error("网关处理响应异常" + e);
            return chain.filter(exchange);
        }
    }

    @Override
    public int getOrder() {
        return -1;
    }

    public Mono<Void> handleNoAuth(ServerHttpResponse response) {
        response.setStatusCode(HttpStatus.FORBIDDEN);
        return response.setComplete();
    }

    public Mono<Void> handleInvokeError(ServerHttpResponse response) {
        response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
        return response.setComplete();
    }
}